<template>
	<view>
		<cu-custom bgColor="bg-gradual-blue" :isBack="true" class="nav-custom">
			<!-- <block slot="backText">返回</block> -->
			<block slot="content">{{ title }}用户</block>
		</cu-custom>
		<view class="app-box" :style="{ height: appHeight + 'px' }">
			<view class="view-sin">
				<view class="r-title">
					<text>用户昵称</text>
					<text style="color: red">*</text>
				</view>
				<view class="r-input">
					<u-input v-model="userInfo.nickName"></u-input>
				</view>
			</view>
			<view class="view-sin">
				<view class="r-title">
					<text>归属机构</text>
					<text style="color: red">*</text>
				</view>
				<view class="r-input flex-bc pr20" @click="$refs.treePicker._show()">
					<view>{{ userInfo.deptName }}</view>
					<u-icon color="#607589" name="arrow-down-fill" size="20"></u-icon>
				</view>
			</view>
			<view class="view-sin">
				<view class="r-title">
					<text>手机号码</text>
					<text style="color: red">*</text>
				</view>
				<view class="r-input">
					<u-input v-model="userInfo.phone" placeholder="请输入手机号"></u-input>
				</view>
			</view>
			<view class="view-sin">
				<view class="r-title">
					<text>邮箱</text>
					<text style="color: red">*</text>
				</view>
				<view class="r-input">
					<u-input v-model="userInfo.email" placeholder="请输入邮箱"></u-input>
				</view>
			</view>

			<view class="view-sin">
				<view class="r-title">
					<text>账号 </text>
					<text style="color: red">*</text>
				</view>
				<view
					class="r-input"
					:class="{
						'r-input-disabled': type == 'edit'
					}"
				>
					<u-input :disabled="type == 'edit'" v-model="userInfo.userName" placeholder="请输入账号"></u-input>
				</view>
			</view>

			<view class="view-sin" v-show="type == 'add'">
				<view class="r-title">
					<text>用户密码</text>
					<text style="color: red">*</text>
				</view>
				<view class="r-input">
					<u-input type="password" v-model="userInfo.password" placeholder="请输入密码"></u-input>
				</view>
			</view>
			<view class="view-sin">
				<view class="r-title">
					<text>用户性别</text>
				</view>
				<view class="flex-vc w100 ml50">
					<u-radio-group v-model="userInfo.sex">
						<u-radio name="0"> 男 </u-radio>
						<u-radio name="1"> 女 </u-radio>
					</u-radio-group>
				</view>

				<!--  -->
			</view>

			<view class="view-sin">
				<view class="r-title">
					<text>角色</text>
				</view>
				<view class="r-input flex-bc pr20" @click="$refs.treePicker2._show()">
					<view class="nop fs24">{{ roleName }}</view>
					<u-icon color="#607589" name="arrow-down-fill" size="20"></u-icon>
					<!-- <listSelect
						:defaultSelect="false"
						v-model="userInfo.roles"
						:list="orlist"
						@confirm="confAreaCode"
						style="width: 490rpx"
					></listSelect> -->
				</view>

				<!--  -->
			</view>
			<view class="view-sin">
				<view class="r-title">
					<text>状态</text>
				</view>
				<view class="flex-vc w100 ml50">
					<u-radio-group v-model="userInfo.status">
						<u-radio name="0"> 正常 </u-radio>
						<u-radio name="1"> 停用 </u-radio>
					</u-radio-group>
				</view>

				<!--  -->
			</view>
			<view class="view-sin">
				<view class="r-title">
					<text>备注</text>
				</view>
				<view class="r-input-box">
					<u-input v-model="userInfo.remarks" type="textarea" :height="180"></u-input>
				</view>

				<!--  -->
			</view>

			<view class="view-btn" @click="userOps">{{ title == '新增' ? '确认添加' : '确认修改' }}</view>
		</view>
		<template v-if="done">
			<ba-tree-picker
				ref="treePicker"
				:multiple="false"
				@select-change="selectChange"
				title="选择机构"
				:localdata="listData"
				:selectedData="selectedDataArea"
				valueKey="id"
				textKey="name"
				childrenKey="children"
			/>
			<ba-tree-picker
				ref="treePicker2"
				:multiple="true"
				@select-change="selectChange2"
				title="选择角色"
				:localdata="orlist"
				:selectedData="selectedData"
				valueKey="id"
				textKey="name"
				childrenKey="children"
			/>
		</template>
	</view>
</template>
<script>
	import SelectArea from '@/components/common/select/SelectArea.vue'
	import listSelect from '@/components/common/select/listSelect.vue'
	import userMagApi from '@/api/user/userMag'
	import baTreePicker from '@/components/ba-tree-picker/ba-tree-picker.vue'
	export default {
		name: 'personMag',
		components: {
			SelectArea,
			listSelect,
			baTreePicker
		},
		data() {
			return {
				type: '',
				appHeight: 0,
				title: '',
				userInfo: {
					deptId: '', //机构id
					deptName: '', // 机构名称
					email: '', //邮箱
					nickName: '', //用户名
					userName: '', //账户
					password: '', //密码
					phone: '', //电话
					projectId: 'e3cc3a226021fdc238bb32550647d767', //项目id
					remarks: '', //备注
					roles: [], //角色数组[角色id]
					sex: '0', //性别（0男1女）
					status: '0' //状态（0正常1停用）
				},

				// listData: [],
				orlist: [],
				selectedData: [],
				selectedDataArea: [],
				done: false
			}
		},
		computed: {
			roleName() {
				let roles = this.userInfo.roles || []
				let item = this.orlist.filter((el) => roles.includes(el.id))
				let arr = item.map((el) => {
					return el.name
				})
				return arr.join('、')
			},
			listData() {
				let deptId = this.UserInfo.dept_id
				console.info(`this.DeptTreeData:`, this.DeptTreeData, this.UserInfo.dept_id)
				let item = this.findItemById(this.DeptTreeData, deptId)
				console.info(`item:`, item)
				if (item) {
					return [item]
				} else {
					return []
				}
			}
		},
		async onLoad(options) {
			if (options && options.data) {
				let postData = JSON.parse(decodeURIComponent(options.data))
				this.title = postData.type == 'add' ? '新增' : '编辑'
				this.type = postData.type
				if (postData.data) {
					const userInfoRes = await userMagApi.getUserPower(postData.data.id)
					this.userInfo = userInfoRes.data.result
					this.password = userInfoRes.data.result.password
					this.selectedDataArea = [this.userInfo.deptId]
					// console.info(` this.userInfo.roles:`, this.userInfo.roles)
					this.selectedData = this.userInfo.roles || []
				} else {
					this.userInfo = {
						deptId: '', //机构id
						deptName: '', // 机构名称
						email: '', //邮箱
						nickName: '', //用户名
						userName: '', //账户
						password: 'Smsl@123456', //密码
						phone: '', //电话
						projectId: 'e3cc3a226021fdc238bb32550647d767', //项目id
						remarks: '', //备注
						roles: [], //角色数组[角色id]
						sex: '0', //性别（0男1女）
						status: '0' //状态（0正常1停用）
					}
				}
				this.done = true
			}
		},
		async mounted() {
			this.appHeight = await this.$getHeight('.nav-custom')
			let magList = this.$getItem('magList')
			this.orlist = magList.map((el, index) => {
				el.label = el.name
				el.value = el.id
				return el
			})
			let normalItem = this.orlist.find((el) => el.label == '普通用户')
			if (normalItem) {
				this.userInfo.roles = [normalItem.value]
			}
			// this.yehuoLogin()
		},
		methods: {
			validatePassword(password) {
				var passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^a-zA-Z\d])[\w\d\S]{8,20}$/
				return passwordRegex.test(password)
			},

			// 输入id，找出id所在的项
			findItemById(tree, id) {
				// 遍历数组中的每一项
				for (let i = 0; i < tree.length; i++) {
					const item = tree[i]

					// 如果当前项的id匹配目标id，则返回当前项
					if (item.id === id) {
						return item
					}

					// 如果当前项有子项，则递归调用该函数在子项中查找目标id
					if (item.children && item.children.length > 0) {
						const found = this.findItemById(item.children, id)
						if (found) {
							return found
						}
					}
				}

				// 如果未找到匹配的项，则返回null
				return null
			},
			//监听选择（ids为数组）
			selectChange(ids, names) {
				this.userInfo.deptName = names
				this.userInfo.deptId = ids[0]
				console.info(`	this.userInfo:`, this.userInfo)
				console.log(ids, names)
			},
			selectChange2(ids, names) {
				this.userInfo.roles = ids
				console.info(`ids, names:`, ids, names)
			},
			valuePass() {
				let userInfo = this.userInfo
				if (userInfo.nickName == '') {
					uni.showToast({
						icon: 'error',
						title: '请输入昵称'
					})
					return false
				}
				if (userInfo.deptId == '') {
					uni.showToast({
						icon: 'error',
						title: '请选择归属机构'
					})
					return false
				}
				if (userInfo.phone == '') {
					uni.showToast({
						icon: 'error',
						title: '请输入手机号'
					})
					return false
				}
				if (!/^1[3456789]\d{9}$/.test(userInfo.phone)) {
					uni.showToast({
						icon: 'error',
						title: '手机号格式错误'
					})
					return false
				}

				if (userInfo.email == '') {
					uni.showToast({
						icon: 'error',
						title: '请输入邮箱'
					})
					return false
				}
				if (!/\S+@\S+\.\S+/.test(userInfo.email)) {
					uni.showToast({
						icon: 'error',
						title: '邮箱格式错误'
					})
					return false
				}
				if (userInfo.userName == '') {
					uni.showToast({
						icon: 'error',
						title: '请输入账号'
					})
					return false
				}
				if (userInfo.password == '') {
					uni.showToast({
						icon: 'error',
						title: '请输入密码'
					})
					return false
				}
				if (!this.validatePassword(userInfo.password)) {
					uni.showToast({
						icon: 'error',
						title: '密码安全强度弱'
					})
					return false
				}
				return true
			},
			async userOps() {
				if (!this.valuePass()) {
					return
				}
				// 新增
				if (this.type == 'add') {
					const resp = await userMagApi.saveUser({
						...this.userInfo,
						roles: this.userInfo.roles
					})
					console.info(`resp:`, resp)
					if (resp.msg == 'success') {
						this.yehuoAddUser(resp.data)
					} else {
						uni.showToast({
							icon: 'error',
							title: resp.msg
						})
					}
				}
				// 编辑用户
				if (this.type == 'edit') {
					const resp = await userMagApi.updateToPost({
						...this.userInfo,
						roles: this.userInfo.roles
					})
					// 修改密码
					if (this.password != this.userInfo.password) {
						const mima = await userMagApi.resetPwd({
							id: this.userInfo.id, // 用户id
							password: this.userInfo.password
						})
					}

					console.info(`resp:`, resp)
					if (resp.msg == 'success') {
						this.yehuoeditUser(resp.data)
					}
				}
			},
			async yehuoAddUser(h5user) {
				try {
					uni.showLoading({
						title: '正在提交'
					})
					const resp = await userMagApi.yhlogin({
						account: 'admin',
						password: 'admin123'
					})
					const Authtoken = resp.headers.authtoken
					const root = await userMagApi.yhroot(Authtoken)
					let organizationId = root.data.result[0].id || 19
					console.info(`resp:`, root)
					const yeUserdata = await userMagApi.yhcreate(
						{
							email: h5user.email,
							mobile: h5user.id,
							name: h5user.nickName,
							organizationId: organizationId
						},
						Authtoken
					)

					const resp2 = await userMagApi.updateYhId({
						Id: h5user.id,
						imId: yeUserdata.data.result.employeeId
					})
					if (resp2.msg == 'success') {
						uni.showToast({
							title: '新增成功'
						})
					}
					this.$hideLoading()
				} catch (error) {
					uni.showToast({
						icon: 'error',
						title: '操作失败'
					})
					this.$hideLoading()
				}
			},
			// edit 野火
			async yehuoeditUser(h5user) {
				try {
					uni.showLoading({
						title: '正在提交'
					})
					const resp = await userMagApi.yhlogin({
						account: 'admin',
						password: 'admin123'
					})
					const Authtoken = resp.headers.authtoken
					const root = await userMagApi.yhroot(Authtoken)
					let organizationId = root.data.result[0].id || 19
					console.info(`resp:`, root)
					const yeUserdata = await userMagApi.yhupdate(
						{
							email: h5user.email,
							mobile: h5user.id, // 电话（对应我们系统中的用户id）
							name: h5user.nickName, // 用户名
							organizationId: organizationId // 组织机构id
						},
						Authtoken
					)

					// const resp2 = await userMagApi.updateYhId({
					// 	Id: h5user.id,
					// 	imId: yeUserdata.data.result.employeeId
					// })
					if (resp2.msg == 'success') {
						uni.showToast({
							title: '操作成功'
						})
					}
					this.$hideLoading()
				} catch (error) {
					uni.showToast({
						icon: 'error',
						title: '操作失败'
					})
					this.$hideLoading()
				}
			}
		}
	}
</script>
<style lang="less">
	.app-box {
		position: relative;
		overflow: hidden;
		width: 750rpx;
		.r-input-disabled {
			background: rgba(174, 174, 174, 0.3) !important;
		}
		.view-sin {
			margin-top: 30rpx;
			width: 750rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 30rpx;
			.r-title {
				width: 154rpx;
				text-align: left;
			}
			.r-input {
				width: 520rpx;
				height: 60rpx;
				border-radius: 4rpx;
				border: 1rpx solid #aeaeae;
				background: #fff;
				align-items: center;
				display: flex;
				padding-left: 10rpx;
			}
			.r-input-box {
				width: 520rpx;
				border-radius: 4rpx;
				border: 1rpx solid #aeaeae;
				background: #fff;
				align-items: center;
				display: flex;
				padding-left: 10rpx;
			}
		}
		.view-btn {
			width: 636rpx;
			height: 80rpx;
			flex-shrink: 0;
			border-radius: 20rpx;
			background: #41a4ff;
			backdrop-filter: blur(15px);
			text-align: center;
			line-height: 80rpx;
			margin: 80rpx auto;
			color: #fff;
		}
	}
</style>
